package com.baidu.servlet;

import com.fd.pojo.Cart;
import com.fd.service.CartService;
import com.fd.service.impl.CartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


public class CartController extends HttpServlet {
    private CartService cartService = new CartServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doRequest(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doRequest(req,resp);
    }
    private void doRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        if ("/addCart".equals(servletPath)){
            addCart(req,resp);
        }else if("/selectCart".equals(servletPath)){
            selectCart(req,resp);
        }else if ("/reGoodsCart".equals(servletPath)){
            reGoodsCart(req,resp);
        }
    }
    //删除根据id购物车商品
    private void reGoodsCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer pid =Integer.parseInt(req.getParameter("pid"));
        boolean b = cartService.reGoodsCart(pid);
        if (b){
            resp.sendRedirect("/selectCart");
        }else {

        }
    }

    //查看购物车
    private void selectCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Cart> cartList = cartService.selectCart();
        HttpSession session = req.getSession();
        session.setAttribute("cartList",cartList);
        req.getRequestDispatcher("/WEB-INF/cart.jsp").forward(req, resp);
    }

    //添加购物车
    private void addCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pid = req.getParameter("pid");
        System.out.println(pid);
        boolean b = cartService.addCart(pid);
        if (b){
            req.getRequestDispatcher("/WEB-INF/shopping.jsp").forward(req, resp);
        }else {
            resp.getWriter().println("加入购物车失败");
            req.getRequestDispatcher("/WEB-INF/shopping.jsp").forward(req, resp);
        }
    }
}
